package com.wms.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wms.entity.BaseWarehouse;
import com.wms.service.BaseWarehouseService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/5/6
 * @desc
 */
@Slf4j
public class BaseWarehouseListener extends AnalysisEventListener<BaseWarehouse> {
    private static final int BATCH_COUNT = 5;
    private List<BaseWarehouse> baseWarehouses = new ArrayList<>();
    private BaseWarehouseService  baseWarehouseService;

    public BaseWarehouseListener(BaseWarehouseService baseWarehouseService) {
        this.baseWarehouseService = baseWarehouseService;
    }

    @Override
    public void invoke(BaseWarehouse data, AnalysisContext context) {
        log.info("解析到一条数据:{}",data);
        baseWarehouses.add(data);
        if (baseWarehouses.size() >= BATCH_COUNT) {
            saveData();
            baseWarehouses.clear();
        }
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", baseWarehouses.size());
        baseWarehouseService.insertBatch(baseWarehouses);
        log.info("存储数据库成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 如果baseWarehouses不为空，需要保存到数据库
        if (!baseWarehouses.isEmpty()) {
            saveData();
        }
        log.info("所有数据解析完成！");
    }
}
